log("this conn build from servotronix demo");

// 通信对象
var conn = null;

// 初始化 连接  websocket  
function connectMC(){
    conn = new MC_CONNECTION(function(){
        log("Connected Servotronix Socket!"); 
    });
    conn.init();        
}

// 发送指令 cmd为指令内容
function doQuery(cmd){
    conn.queryMC(cmd,function(result){
        console.log(result);//消息返回
    });
}

function handleError(result,cmd) {
	var returnVal = parseInt(result);
	if (!isNaN(returnVal) && returnVal > 0) {
		console.log("error: " + cmd + "\n" + result + "\n\n");
		return true;
	}
	return false;
}

// 通信实现
function MC_CONNECTION(callback) {
	var conn = this;
	this.WSPORT = 3010;
	this.IP = window.location.hostname;
	this.socketQueueId = 0;
	this.socketQueue = {};
	this.ws = null;
	this.init = function() {
		try {
			conn.ws = new WebSocket("ws://" + this.IP + ":" + this.WSPORT);
			if (typeof(callback) === 'function')
				conn.ws.onopen = function(){console.log("websocket opened!");callback();};
			conn.ws.onmessage = function (msg) {
			  conn.handleMessage(msg);
			};
			conn.ws.onerror = function(e){console.log("error:" + e);};
			conn.ws.onclose = function(){console.log("websocket closed!");};
		} catch (err) {
			log(err.message);
			alert(err.message);
		}
	};
	this.handleMessage = function(e) {
		var data = JSON.parse(e.data);
		var result = data['msg'].replace(/[\r]+/g,'');
		var isErrorFrame = (result.indexOf("$ERRORFRAME$") === 0);
		if (isErrorFrame) {
			// handle error
		} else if (typeof(data['cmd_id']) !== 'undefined' && data['cmd_id'] === -1) {// Server Announcment
			if (result.indexOf(">>>") === 0) { // TP DIALOG MSG
				// handle dialog message
			} else { // Other Server announcements (probably errors)
				// handle message
			}
		}
		if (typeof(data['cmd_id']) !== 'undefined' && typeof(conn.socketQueue['i_'+data['cmd_id']]) === 'function'){
			var execFunc = conn.socketQueue['i_' + data['cmd_id']];
			setTimeout(function(){
				execFunc(result,data['cmd']);
				delete conn.socketQueue['i_'+data['cmd_id']]; // to free up memory..
				delete data;
			},0);
		}
	};
	this.queryMC = function(query, callback){
		conn.socketQueueId++;
		if (typeof(callback) === 'function'){
			conn.socketQueue['i_'+conn.socketQueueId] = callback;
		}
		var jsonData = JSON.stringify({
			'cmd_id':conn.socketQueueId,
			'msg':query
		});
		conn.ws.send(jsonData);
	};
}


/* update timer 更新定时器 */
function getMessageData(){
   if(conn && data_login){
		conn.queryMC('?errorhistory',function(result){
			// console.log(result);
			data_message=result;
		});
	}	
};
var messageInterval = setInterval(getMessageData,1000);

//点位
function getPointData(){
	if(conn && data_login){
		conn.queryMC('?TP_GET_COORDINATES',function(result){
			// console.log(result);
			var controllerData=result.split(";");
			data_point_world = controllerData[1].substr(1,controllerData[1].length-2).split(",");
			data_point_joint = controllerData[3].substr(1,controllerData[3].length-2).split(",");
		});
	}	
};
var pointInterval = setInterval(getPointData,200);

//状态 tp_stat
//Enabled, isMoving, isSetteled, errorString, velocityRate, bipRequest
function getStatData(){
	if(conn && data_login){
		conn.queryMC('?TP_STAT',handleStat);
   	}
};
var statInterval = setInterval(getStatData,200);

function handleStat(statString) {
	var stat = JSON.parse(statString);
	//var stat = statString.split(",");
	
	if(stat.ENABLE){
		data_servo = "on";
	}
	else{
		data_servo = "off";
	}

	// if(stat.MOVING && !stat.SETTELED){
	// 	data_runstate = "run";
	// }
	// else{
	// 	data_runstate = "stop";
	// }

	// errorString	=	stat.ERRMESSAGE;
	data_speed_t = stat.VRATE;
	// bipRequest	=	stat.BIP; // NOT WORKING
	
	if(data_fileLoad){
		conn.queryMC('?'+data_file_name+'.upg.status',function(result){//这个要改为自己实现
			// console.log("checkTaskState "+result);

			var fileStat = result.split(" ");

			var state_tmp = fileStat[1].split(":");
			var state = state_tmp[1];
			var stateID = state_tmp[0];

			var line = fileStat[5];
			log("running line:"+line);

			if((stat.MOVING && !stat.SETTELED) || stateID == 1){
				data_runstate = "run";
			}
			else{
				data_runstate = "stop";
			}
		});
	}
	else{
		if(stat.MOVING && !stat.SETTELED){
			data_runstate = "run";
		}
		else{
			data_runstate = "stop";
		}
	}
}

//状态 tp_get_task_state
//Enabled, isMoving, isSetteled, errorString, velocityRate, bipRequest
// function getFileData(){
// 	if(conn && data_login){
// 		conn.queryMC('?tp_get_task_state',function(result){

// 			console.log("checkTaskState "+result);
			// var state = result.split(",")[0];
			// var stateID = result.split(",")[1];
			// var line = result.split(",")[2];
			// var color;
			// var changedTaskFlag = (stateID != currTaskState);
			// currTaskState = stateID;
			// switch (stateID) {
			// 	case "1":
			// 		color = "greenText";
			// 		if (changedTaskFlag) {
			// 			disableAllButtons();
			// 			$("#program-btn-idle").removeAttr("disabled");
			// 			$("#program-btn-kill").removeAttr("disabled");
			// 			$(".program-header").css("pointer-events","none");
			// 			editor.setReadOnly(true);
			// 		}
			// 		break;
			// 	case "2": // stopped
			// 		$(".program-header").css("pointer-events","auto");
			// 		editor.setReadOnly(false);
			// 		color = "redText";
			// 		if (changedTaskFlag) {
			// 			disableAllButtons();
			// 			$("#program-file-list").selectmenu("disable");
			// 			$("#program-btn-run").removeAttr("disabled");
			// 			$("#program-btn-kill").removeAttr("disabled");
			// 			$("#program-btn-stepover").removeAttr("disabled");
			// 			$("#program-btn-stepinto").removeAttr("disabled");
			// 			$("#program-btn-stepout").removeAttr("disabled");
			// 		}
			// 		break;
			// 	case "4":
			// 		$(".program-header").css("pointer-events","auto");
			// 		editor.setReadOnly(false);
			// 		color = "redText";
			// 		if (changedTaskFlag) {
			// 			disableAllButtons();
			// 			$("#program-btn-run").removeAttr("disabled");
			// 			$("#program-btn-kill").removeAttr("disabled");
			// 		}
			// 		break;
			// 	case "10":
			// 		$(".program-header").css("pointer-events","auto");
			// 		editor.setReadOnly(false);
			// 		color = "redText";
			// 		if (changedTaskFlag) {
			// 			disableAllButtons();
			// 			$("#program-file-list").selectmenu("disable");
			// 			$("#program-btn-unload").removeAttr("disabled");
			// 			$("#program-btn-run").removeAttr("disabled");
			// 			$("#program-btn-stepover").removeAttr("disabled");
			// 			$("#program-btn-stepinto").removeAttr("disabled");
			// 			$("#program-btn-stepout").removeAttr("disabled");
			// 		}
			// 		break;
			// 	default:
			// 		$(".program-header").css("pointer-events","auto");
			// 		editor.setReadOnly(false);
			// 		color = "redText";
			// 		break;
			// }
			// $("#program-file-status-bar").html("<span class='" + color + "'>" + state + "</span> | " + translator.getStr("txtCurrentLine") + " " + line + "<span style='float:right;'>Selected Robot: " + currRobot + "</span>");
			// highlightLine("0," + line);
// 		});
//    	}
// };
// var fileInterval = setInterval(getFileData,400);
